package com.mylib.libcore.network.interceptor;

import android.util.Log;

import com.mylib.libcore.utils.UIUtils;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 自定义请求日志
 */
public class LoggingInterceptor implements Interceptor {

    private final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();

        RequestBody requestBody = request.body();
        String body = "";
        if (!UIUtils.isEmpty(requestBody)) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            body = buffer.readString(charset);
        }
        System.out.println("发送请求"+request.url()+"\n方法"+request.method()+"\n请求header:"+request.headers()+"\n请求body:"+body);
        Log.d("发送请求" , request.url() + "\n方法" + request.method() + "\n请求header:" + request.headers() + "\n请求body:" + body);
        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        ResponseBody responseBody = response.body();
        String rBody = null;

        BufferedSource source = responseBody.source();
        MediaType contentType = responseBody.contentType();
        if (contentType != null && contentType.toString().contains("json")) {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                e.printStackTrace();
            }
            rBody = buffer.clone().readString(charset);
        }
        System.out.println("收到响应"+response.code()+"\n响应消息"+response.message()+"\n响应url:"+response.request().url()+"\n响应body:"+body+"\n响应rbody:"+rBody);
        Log.d("收到响应",response.code()+"\n响应消息"+response.message()+"\n响应url:"+response.request().url()+"\n响应body:"+body+"\n响应rbody:"+rBody);
        return response;
    }


    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }

}
